<?php
namespace App\Http\Controllers\Api\Tg;

use Carbon\Carbon;

use App\Models\Bill\Bill;

use App\Models\Mall\MallMaster;

use App\Models\Tg\Tg;  //团购维护主表

use App\Models\ConfigureFunction; //功能配置表

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\Customer\Customer;

class TgCartController extends Controller
{

    /**
     * 加入购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addCart(Request $request)
    {

        $goods_amount = $request->input('goods_amount');
        $parent_bill_no = $request->input('bill_no', 0);
        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $mallID = $request->input('mallID', 0);
        $tuan_id = $request->input('tuan_id');
        $postID = $request->input('postID');

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        if ( !$tuan_id || !ebsig_is_int($tuan_id) ) {
            return response()->json(['code' => 100003, 'message' => '缺少参数：tuan_id']);
        }

        if ( !$postID || !ebsig_is_int($postID) ) {
            return response()->json(['code' => 100004, 'message' => '缺少参数：postID']);
        }

        if ( !$goods_amount || !ebsig_is_int($goods_amount) ) {
            $goods_amount = 1;
        }

        //获取团购信息
        $tuan_data = Tg::getCache($tuan_id);
        if ( !$tuan_data ) {
            return response()->json(['code' => 100005, 'message' => '团购不存在']);
        }
        if ( $tuan_data['useFlg'] == 0 ) {
            return response()->json(['code' => 100006, 'message' => '该团购已结束']);
        }

        /**
         * ===================================
         * 时间检查
         * ===================================
         */

        if ( $tuan_data['start_time'] > Carbon::now() ) {
            return response()->json(['code' => 100007, 'message' => '该团购未开始']);
        }

        $end_time = $tuan_data['end_time'];

        //如果是参团情况，结束时间最大为主订单的创建时间+24小时
        if ( $parent_bill_no ) {
            //查询主订单创建时间
            $parent_bill_data = Bill::find($parent_bill_no);
            if ( $parent_bill_data ) {
                $end_time = date("Y-m-d H:i:s",strtotime($parent_bill_data->createTime . " +24 hour"));
            }
        }

        if ( $end_time < Carbon::now() ) {
            return response()->json(['code' => 100008, 'message' => '该团购已结束']);
        }


        //团购商品信息
        $tuan_goods = array();
        if ( !empty($tuan_data['goods']) ) {
            foreach ( $tuan_data['goods'] as $item ) {
                if ( $item['postID'] == $postID ) {
                    $tuan_goods = $item;
                    break;
                }
            }
        }
        if ( empty($tuan_goods) ) {
            return response()->json(['code' => 100009, 'message' => '团购商品信息未找到']);
        }

        $goods_buy_count = json_decode(Redis::get('G_WDH_TG_GOODS_BUY_NUM_' . $tuan_id . '_' .  $postID), true);

        if ( $tuan_goods['tuan_store'] < $goods_buy_count + $goods_amount ) {
            return response()->json(['code' => 100010, 'message' => '库存不足']);
        }

        $tuan_price = round($tuan_goods['tuan_price'] * $goods_amount, 2);

        //结算配置，获取配送运费
        $bill_config = $tuan_data['config'];
        $freight_free = 0;
        if ( $bill_config ) {
            $freight_free = $bill_config['freight_free'];
        }


        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');

        if ( $is_open_choose_mall == 1 ) {

            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 100012, 'message' => '请先选择门店']);
            }

            //查询门店信息
            $mall = MallMaster::getCache($mallID);
            if (!$mall) {
                return response()->json(['code' => 100013, 'message' => '门店不存在']);
            }
            
            //指定门店
            $activity_mall = $tuan_data['activity_mall'];
            if ( $bill_config && $bill_config['mall_range_type'] == 2 && !empty($activity_mall) ) {
                if ( !in_array($mallID, $activity_mall) ) {
                    return response()->json(['code' => 100014, 'message' => '当前选择门店不参与此次团购活动']);
                }
            }

        }

        //查询会员信息
        $cust_data = Customer::find($pcustID);
        if (!$cust_data) {
            return response()->json(['code' => 1000015, 'message' => '会员信息不存在']);
        }

        $tuan_bill_data = array(
            'tuan_id' => $tuan_id,
            'parent_bill_no' => $parent_bill_no,
            'freight_free' => $freight_free,
            'ziti' => 1,
            'sendTypeID' => 2,
            'mallID' => $mallID,
            'mallCode' => isset($mall['mallCode']) ? $mall['mallCode'] : '',
            'mallName' => isset($mall['mallName']) ? $mall['mallName'] : '',
            'bill_totalMoney' => $tuan_price,
            'bill_totalPaid' => $tuan_price,
            'bill_totalPoints' => 0,
            'bill_pointsPrice' => 0,
            'bill_subtract_money' => 0,
            'bill_points_money' => 0,
            'bill_balance_money' => 0,
            'bill_coupon_money' => 0,
            'bill_card_money' => 0,
            'bill_payable' => $tuan_price,
            'bill_total_amount' => $goods_amount,
            //订单类型；1、正常订单 2、特价购订单 3、闪购订单 4、积分订单 5、补货单 6、换货单 7、众筹单 8、预售订单 9、团购订单 10、虚拟商品订单
            'billType' => 9,
            'remark' => null,
            'payPwd' => null,
            'payment_method_id' => null,
            'send_region_id' => 0,
            'custID' => $cust_data['custID'],
            'cardNo' => $cust_data['cardNo'],
            'goods' => array(
                [
                    'goodsID' => $tuan_goods['goodsID'],
                    'postID' => $tuan_goods['postID'],
                    'goodsName' => $tuan_goods['goodsName'],
                    'product_code' => $tuan_goods['product_code'],
                    'pic' => $tuan_goods['img_link'],
                    'one_level_spec_str' => $tuan_goods['one_level_spec_str'],
                    'two_level_spec_str' => $tuan_goods['two_level_spec_str'],
                    'spec' => $tuan_goods['spec'],
                    'goods_amount' => $goods_amount,
                    'marketPrice' => $tuan_goods['marketPrice'],
                    'salePrice' => $tuan_goods['salePrice'],
                    'price' => $tuan_goods['tuan_price'],
                    'goods_pointsPrice' => 0,
                    'goods_from' => 1,
                    'addPoints' => 0,
                    'salePoints' => 0,
                    'goodsWeight' => $tuan_goods['goodsWeight'],
                    'promotion' => null,
                    'promotionID' => 0,
                    'goodsType' => 1,
                    'virtual_id' => 0,
                    'virtual_name' => null,
                    'virtual_type' => 1,
                    'goods_groupID' => 0,
                    'goods_remark' => '',
                    'recordPrice' => 0
                ]
            ),
            'pay' => []
        );

        Redis::setex('TUAN_BILL_DATA_' .  $pcustID, 360000, json_encode($tuan_bill_data,true));

        return response()->json(['code' => 200, 'message' => 'ok']);

    }
}